package com.beagle.njddapp.ui.activity.oil;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.beagle.njddapp.R;
import com.beagle.njddapp.base.BaseMvpActivity;
import com.beagle.njddapp.bean.ZkBean;
import com.beagle.njddapp.bean.oil.OilHomeBean;
import com.beagle.njddapp.event.OilChangeEvent;
import com.beagle.njddapp.event.OilOrderEvent;
import com.beagle.njddapp.event.SkEnent;
import com.beagle.njddapp.ui.fragment.CommonMapfragment;
import com.beagle.njddapp.ui.presenter.OilOrderDetailPresenter;
import com.beagle.njddapp.ui.view.OilOrderDetailView;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.beagle.njddapp.weight.dialog.MapDialog;
import com.beagle.njddapp.weight.dialog.OilDIalog;
import com.beagle.njddapp.weight.dialog.ShouKuanDIalog;
import com.blankj.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author hxx
 * @date 2021-03-18 10:36
 * 加油订单详情
 */
public class OilOrderDetailActivity extends BaseMvpActivity<OilOrderDetailView, OilOrderDetailPresenter> implements OilOrderDetailView, ShouKuanDIalog.skDialogHandleCallback, OilDIalog.OilDialogHandleCallback {

    @BindView(R.id.commom_title_tv)
    TextView tvTitle;
    @BindView(R.id.common_container)
    RelativeLayout container;
    private int orderId;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_ordernum)
    TextView tvOrderNumber;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_user_name)
    TextView tvName;
    @BindView(R.id.tv_address)
    TextView tvAddrss;
    @BindView(R.id.tv_caozuo)
    TextView tvCz;
    @BindView(R.id.ll_pj)
    LinearLayout llPj;
    @BindView(R.id.iv2)
    ImageView iv2;
    @BindView(R.id.iv3)
    ImageView iv3;
    @BindView(R.id.iv4)
    ImageView iv4;
    @BindView(R.id.iv5)
    ImageView iv5;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.iv_pay)
    ImageView ivPay;
    @BindView(R.id.ll_zk)
    LinearLayout llZk;
    @BindView(R.id.rl_pay)
    RelativeLayout rlPay;
    @BindView(R.id.tv_act)
    TextView tvAct;
    @BindView(R.id.rl_pay_count)
    RelativeLayout rlPayType;
    @BindView(R.id.tv_order_pay_type)
    TextView tvPayType;
    private OilDIalog oilDIalog;
    private OilHomeBean oilHomeBean;
    private ShouKuanDIalog shouKuanDIalog;
    private MapDialog mapDialog;
    @Override
    public int getLayoutId() {
        return R.layout.activity_oilorder_detail;
    }

    @Override
    public void init() {
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        tvTitle.setText("订单详情");
        container.setBackgroundColor(Color.WHITE);
        orderId=getIntent().getIntExtra("orderId",-1);
        presenter.getOrderDetail(orderId);
    }

    private void addFragment() {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); //去掉切换Fragment时闪动的动画效果
        CommonMapfragment commonMapfragment=new CommonMapfragment();
        Bundle bundle=new Bundle();
        if (!TextUtils.isEmpty(oilHomeBean.getMeshLatitude())) {
            double lat=Double.parseDouble(oilHomeBean.getMeshLatitude());
            double lnt=Double.parseDouble(oilHomeBean.getMeshLongitude());
            bundle.putDouble("latitude",lat);
            bundle.putDouble("longitude",lnt);
        }
        commonMapfragment.setArguments(bundle);
        transaction.replace(R.id.map_container, commonMapfragment);
        transaction.commitNowAllowingStateLoss();
    }

    @OnClick({R.id.common_back_iv,R.id.tv_caozuo,R.id.tv_address,R.id.iv_address})
    public void onCLick(View view){
        switch (view.getId()){
            case R.id.tv_address:
            case R.id.iv_address:
                if (mapDialog==null){
                    mapDialog=new MapDialog(this);
                }
                mapDialog.show();
                if (!TextUtils.isEmpty(oilHomeBean.getMeshLatitude())) {
                    double lat=Double.parseDouble(oilHomeBean.getMeshLatitude());
                    double lnt=Double.parseDouble(oilHomeBean.getMeshLongitude());
                    mapDialog.setLat(lat);
                    mapDialog.setLnt(lnt);
                }
                mapDialog.setAddress(tvAddrss.getText().toString());
                break;
            case R.id.common_back_iv:
                onBackPressed();
                break;
            case R.id.tv_caozuo:
                if (oilHomeBean==null){
                    return;
                }
                if (oilHomeBean.isPayed()){
                    return;
                }
                if ("waiting".equals(oilHomeBean.getOrderState())){
                    presenter.confirmed(orderId);
                }else  if ("confirmed".equals(oilHomeBean.getOrderState())){
                    presenter.arrived(orderId);
                }else if ("arrived".equals(oilHomeBean.getOrderState())){
                    if(oilDIalog==null){
                        oilDIalog=new OilDIalog(this);
                        oilDIalog.setOilDialogHandleCallback(this);
                    }
                    oilDIalog.show();
                    oilDIalog.setOrderId(orderId);
                }else if ("finished".equals(oilHomeBean.getOrderState())){
                    if (oilHomeBean.getPaymentType()==5){
                        if (shouKuanDIalog==null){
                            shouKuanDIalog=new ShouKuanDIalog(this);
                            shouKuanDIalog.setSkDialogHandleCallback(this);
                        }
                        shouKuanDIalog.show();
                    }
                }
                break;

        }
    }


    @Override
    public OilOrderDetailView getMvpView() {
        return this;
    }

    @Override
    public OilOrderDetailPresenter createPresenter() {
        return new OilOrderDetailPresenter();
    }

    @Override
    public void showOrder(OilHomeBean result) {
        oilHomeBean=result;
        addFragment();
        tvNumber.setText(result.getMeshNum());
//        tvCount.setText(result.getMeter()+"L");
        tvType.setText(result.getMeshTypeName());
        tvOrderNumber.setText(result.getOrderNum());
        tvName.setText(result.getSenderName());
        tvPhone.setText(result.getSenderPhone());
        if (TextUtils.isEmpty(result.getMeshAddress())){
            if (!TextUtils.isEmpty(oilHomeBean.getMeshLatitude())){
                double lat=Double.parseDouble(oilHomeBean.getMeshLatitude());
                double lnt=Double.parseDouble(oilHomeBean.getMeshLongitude());
                GeocodeSearch geocoderSearch = new GeocodeSearch(this);
                geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener(){

                    @Override
                    public void onGeocodeSearched(GeocodeResult result, int rCode) {


                    }
                    @Override
                    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                        try {
                            tvAddrss.setText(result.getRegeocodeAddress().getFormatAddress());
                        }catch (Exception e){

                        }
                    }});
                com.amap.api.services.core.LatLonPoint lp = new  com.amap.api.services.core.LatLonPoint(lat,lnt);
                RegeocodeQuery query = new RegeocodeQuery(lp,200,GeocodeSearch.AMAP);
                geocoderSearch.getFromLocationAsyn(query);
            }
        }else {
            tvAddrss.setText(result.getMeshAddress());

        }
        if (oilHomeBean.isPayed()){
            tvAct.setText(result.getTotalAmount());
            presenter.getOrderInfo(orderId);
            rlPayType.setVisibility(View.VISIBLE);
            tvPrice.setText(result.getPaymentTypeName());
            if (!TextUtils.isEmpty(result.getPaymentTypeName())){
                if(result.getPaymentTypeName().contains("支付宝")){
                    ivPay.setImageResource(R.mipmap.icon_alipay);
                }else if (result.getPaymentTypeName().contains("微信")){
                    ivPay.setImageResource(R.mipmap.icon_wxpay);
                }
            }
            tvCz.setText("已完成");
            tvCz.setBackground(getResources().getDrawable(R.drawable.bg_login_btn));
            if (oilHomeBean.getVoteRate()>0){
                llPj.setVisibility(View.VISIBLE);
                if (oilHomeBean.getVoteRate()==1){
                    iv5.setImageResource(R.mipmap.score_star_nor);
                    iv4.setImageResource(R.mipmap.score_star_nor);
                    iv3.setImageResource(R.mipmap.score_star_nor);
                    iv2.setImageResource(R.mipmap.score_star_nor);
                }else if (oilHomeBean.getVoteRate()==2){
                    iv5.setImageResource(R.mipmap.score_star_nor);
                    iv4.setImageResource(R.mipmap.score_star_nor);
                    iv3.setImageResource(R.mipmap.score_star_nor);
                }else if (oilHomeBean.getVoteRate()==3){
                    iv5.setImageResource(R.mipmap.score_star_nor);
                    iv4.setImageResource(R.mipmap.score_star_nor);
                }else if (oilHomeBean.getVoteRate()==4){
                    iv5.setImageResource(R.mipmap.score_star_nor);
                }
            }
            return;
        }
        if ("waiting".equals(result.getOrderState())){
            tvCz.setText("待确认");
            tvCz.setBackground(getResources().getDrawable(R.drawable.bg_login_btn));
        }else if ("confirmed".equals(result.getOrderState())){
            tvCz.setText("确认到达");
            tvCz.setBackground(getResources().getDrawable(R.drawable.bg_login_btn));
        }else if ("arrived".equals(result.getOrderState())){
            tvCz.setText("完成加油");
            tvCz.setBackground(getResources().getDrawable(R.drawable.bg_login_btn));
        }else if ("finished".equals(result.getOrderState())){
            if (result.getPaymentType()==5){
                tvCz.setText("确认收款");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_login_btn));
            }else {
                tvCz.setText("等待支付");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
            }

        }
    }

    @Override
    public void showArrived() {
        ToastUtils.showShort("操作成功  请在加油完成后进行完成加油操作");
        oilHomeBean.setOrderState("arrived");
        tvCz.setText("完成加油");
    }

    @Override
    public void showSubmit() {
        ToastUtils.showShort("操作成功  请等待订单发起人发起支付");
        EventBus.getDefault().post(new OilChangeEvent(true));
        oilHomeBean.setOrderState("finished");
        tvCz.setText("等待支付");
        tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
    }

    @Override
    public void shoukuan() {
        ToastUtils.showShort("收款成功");
        oilHomeBean.setPayed(true);
        tvCz.setText("已完成");
        EventBus.getDefault().post(new SkEnent());
    }

    @Override
    public void showJiedan(int orderId) {
        ToastUtils.showShort("操作成功 ");
        oilHomeBean.setOrderState("confirmed");
        tvCz.setText("确认到达");
        List<OilHomeBean> list=new ArrayList<>();
        list.add(oilHomeBean);
        EventBus.getDefault().post(new OilOrderEvent(list));
    }


    @Override
    public void showZkInfo(ZkBean zkBean) {
        llZk.setVisibility(View.VISIBLE);
        rlPay.setVisibility(View.VISIBLE);
        tvAct.setText(zkBean.getActualPrice());
        String price=decimalFormat.format(Double.parseDouble(zkBean.getOilPrice())*Double.parseDouble(zkBean.getMeter()));
        tvPayType.setText(price+"元");

        if(!TextUtils.isEmpty(zkBean.getDiscountOneName())){
            addZk(zkBean.getDiscountOneName()+"-"+zkBean.getDiscountOneValue()+"%",zkBean.getDiscountOneCut());
        }
        if(!TextUtils.isEmpty(zkBean.getDiscountTwoName())){
            addZk(zkBean.getDiscountTwoName()+"-"+zkBean.getDiscountTwoValue()+"%",zkBean.getDiscountTwoCut());
        }

    }
    java.text.DecimalFormat decimalFormat =new java.text.DecimalFormat("#.##");

    public void addZk(String name,String price){
        View view=getLayoutInflater().inflate(R.layout.item_zk,null);
        TextView tvNmae=view.findViewById(R.id.title_tv);
        TextView tvCount=view.findViewById(R.id.tv_zk);
        tvNmae.setText(name);
        tvCount.setText("-"+decimalFormat.format(Double.parseDouble(price))+"元");
        llZk.addView(view);

    }


    @Override
    public void onError(String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void shouKuan(String count, String price) {
        presenter.confirmOrderPayment(oilHomeBean,count,price);

    }

    @Override
    public void oilOk(int orderId, String count) {
        presenter.submit(orderId,count);

    }
}
